
package lagrangepolynomial;

//import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
//import java.awt.Graphics2D;
import java.util.LinkedList;


public class Graph extends Component {
    
    LinkedList<DrawableFunction> list = new LinkedList<>();
    
    int frameWidth;
    int frameHeight;
    int L, R, B, T;
    double h;
    
    Color color = Color.red;
    
    public Graph(int frameWidth, int frameHeight, int L, int R, int B, int T, double h) {
        this.frameWidth = frameWidth;
        this.frameHeight = frameHeight;
        this.L = L;
        this.R = R;
        this.B = B;
        this.T = T;
        this.h = h;
    }
    
    public void add(DrawableFunction df) {
        list.add(df);
    }
    
    @Override
    public void paint(Graphics g) {
        this.drawCoordinateSystem(g);
//        Graphics2D gr = (Graphics2D) g;
//        gr.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));    //Просто делаю линию потолще
        for (DrawableFunction df : list) {
            g.setColor(color);      //можно использовать и g, и gr
            for (double x = L; x <= R; x+=h)
                drawLineFromDec(g, x, df.f(x), x + h, df.f(x + h));
            this.setNextColor();
        }
    }
    
    private int xFromDec(double x) {
        return (int) ((x-L) / (R-L) * frameWidth);
    }
    private int yFromDec(double y) {
        return (int) ((T-y) / (T-B) * frameHeight);
    }
    
    private void setNextColor() {
        color = Color.blue;     //Можно сделать какую-нибудь классную штуку :D Попробуй свернуть и развернуть окно приложения
    }
    private void drawLineFromDec(Graphics g, double x1, double y1, double x2, double y2) {
        g.drawLine(xFromDec(x1), yFromDec(y1), xFromDec(x2), yFromDec(y2));
    }
    
    private void drawCoordinateSystem(Graphics g) {
        g.setColor(Color.black);
        drawLineFromDec(g, L, 0, R, 0);
        drawLineFromDec(g, 0, B, 0, T);
        g.setColor(color);
    }
}
